package com.huitone.smspfm.interfacz.tasks;

import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.connection.RedisConnection;

import com.bin.common.utils.StringUtils;
import com.huitone.smspfm.interfacz.logger.ExtLogger;
import com.huitone.smspfm.interfacz.model.SmsSpeedStatistics;
import com.huitone.smspfm.interfacz.core.AppStaticConfigs;
import com.huitone.smspfm.redis.pipeline.PipelineOpts.ABExcuteCommands;

/**   
* @Title SmsSpeedTask.java 
* @Package com.huitone.smspfm.interfacz.tasks 
* @Description 维护本地短信流量统计，同步缓存
* @author ouzaihui   
* @date 
* @version V1.0   
*/
public class SmsSpeedStatisticsTask extends Thread {
	
	private static final ExtLogger logger = ExtLogger.create(SmsSpeedStatisticsTask.class);

	
	private long excuteIntevel = 60000;
	
	private int saveTimeUnit = 60;
	
	private Set<String> removeSet = new HashSet<String>();
	
	private boolean keepGoing = true;
	private ScheduledExecutorService timerService = Executors.newSingleThreadScheduledExecutor();
	
	@Override
	public void run() {
		

		//开启定时保存数据线程
		startSpeedCacheSaveTask();
		
		while(!this.isInterrupted() && isKeepGoing()) {
			
			Iterator<Entry<String, SmsSpeedStatistics>> iterator = AppStaticConfigs.smsSpeedMap.entrySet().iterator();
			
			
			Map<byte[], byte[]> hashMap = new HashMap<byte[], byte[]>();
			
			while (iterator.hasNext()) {
				
				Entry<String, SmsSpeedStatistics> entry = iterator.next();
			
				String key = entry.getKey();
				SmsSpeedStatistics smsSpeed = entry.getValue();
				hashMap.put(AppStaticConfigs.stringRedisSerializer.serialize(key), AppStaticConfigs.stringRedisSerializer.serialize(smsSpeed.toRedisString()));
				logger.info(key+":"+smsSpeed.toRedisString());
				if( ! smsSpeed.isTimeOut(System.currentTimeMillis(),AppStaticConfigs.smsSpeedTimeOut)){
					logger.debug("清除本地数据: "+key);
					removeSet.add(key);
				}
				

			}
			
			
			//本地数据同步至redis	
			if (hashMap != null && hashMap.size() > 0) {
//				logger.info("更新至缓存  " + hashMap.size());
				AppStaticConfigs.pipelineOpts.save(new ABExcuteCommands() {
					@Override
					public void excute(RedisConnection connection) {
						connection.hMSet(AppStaticConfigs.smsSpeedCacheB,
								hashMap);
					}
				});
			}
			//清除本地过期数据
			if (removeSet != null && removeSet.size() > 0) {
				for (String key : removeSet) {
					AppStaticConfigs.smsSpeedMap.remove(key);
				}
				removeSet.clear();
			}
			
			

			
			try {
				Thread.sleep(excuteIntevel);
			} catch (InterruptedException e) { e.printStackTrace();}
		}
		
		logger.info("短信流量统计线程正在退出");
		
	}
	
	private void startSpeedCacheSaveTask() {
		//保存REDIS数据
//		TimerTask timerTask2 = new TimerTask() {
//
//			@Override
//			public void run() {
//				try {
//					Cursor<Entry<Object, Object>> objList = AppStaticConfigs.hashOpts
//							.scan(AppStaticConfigs.smsSpeedCache,
//									ScanOptions.NONE);
//					while (objList.hasNext()) {
//						Entry<Object, Object> entryObj = objList.next();
//						Object key = entryObj.getKey();
//						Object value = entryObj.getValue();
//
//						//  写日志文件保存到磁盘
//						// logger.speed("["+StringUtils.toString(key)+"] ["+StringUtils.toString(value)+"]");
//						SmsSpeedStatistics smsSpeed = SmsSpeedStatistics
//								.parseJson(StringUtils.toString(value));
//						if (smsSpeed != null) {
//							if (!smsSpeed.isTimeOut(System.currentTimeMillis(),
//									saveTimeUnit * 1000)) {
//								logger.speed("[" + StringUtils.toString(key)
//										+ "] [" + smsSpeed.toRedisString()
//										+ "]");
//							}
//						}
//
//					}
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//
//			}
//		};
		
		//保存本地数据
		TimerTask timerTask = new TimerTask() {

			@Override
			public void run() {
				try {
					if (AppStaticConfigs.smsSpeedMap.size() > 0) {
						Iterator<String> it = AppStaticConfigs.smsSpeedMap
								.keySet().iterator();
						while (it.hasNext()) {
							String key = it.next();
							SmsSpeedStatistics smsSpeed = AppStaticConfigs.smsSpeedMap
									.get(key);
							if (smsSpeed != null) {
								if (!smsSpeed.isTimeOut(
										System.currentTimeMillis(),
										saveTimeUnit * 1000)) {
									logger.speed("["
											+ StringUtils.toString(key) + "] ["
											+ smsSpeed.toRedisString() + "]");
								}
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		};
		Calendar cal = Calendar.getInstance();
		int s = 60 - cal.get(Calendar.SECOND);
		
		timerService.scheduleAtFixedRate(timerTask, s, saveTimeUnit, TimeUnit.SECONDS);

	}


	public boolean isKeepGoing() {
		return keepGoing;
	}

	public void setKeepGoing(boolean keepGoing) {
		this.keepGoing = keepGoing;
	}

	@Override
	public void destroy() {
		this.setKeepGoing(false);
		this.interrupt();
		if(this.timerService != null){
			this.timerService.shutdown();
		}
		this.timerService = null;
	}

}
